﻿using Manox.Libs.Networking;


namespace Manox.Libs.ODB
{
    /// <summary>
    /// Object database synchronizer client.
    /// </summary>
    public class ObjectDatabaseSynchronizerClient : ObjectDatabaseSynchronizer
    {
        /// <summary>Network manager.</summary>
        public INetworkClient NetworkNode;


        /// <summary>
        /// Set network client.
        /// </summary>
        /// <param name="networkNode"></param>
        public void SetNetworkClient(INetworkClient networkNode)
        {
            this.NetworkNode = networkNode;

            this.NetworkNode.RegisterListener<ODBSynchronizationMessage>(this.ProcessNetworkMessage);
        }

        /// <summary>
        /// Dispose.
        /// </summary>
        public override void OnDestroy()
        {
            this.NetworkNode.UnregisterListener<ODBSynchronizationMessage>(this.ProcessNetworkMessage);
        }

        /// <summary>
        /// Send update message.
        /// </summary>
        /// <param name="message"></param>
        public override void SendUpdateMessage(ODBSynchronizationMessage message)
        {
            byte[] data;
            int dataLength;

            MessagePacker.Pack(message, out data, out dataLength);

            this.NetworkNode.Send(data, dataLength);
        }

        /// <summary>
        /// Synchronize.
        /// </summary>
        public void Synchronize()
        {         
            ODBSynchronizationMessage newMessage = new ODBSynchronizationMessage();
            newMessage.EventArgs = new ODBSynchronizerRequestEventArgs();

            this.SendUpdateMessage(newMessage);
        }
    }
}
